package com.apkfuns.jsbridge.view;

import com.apkfuns.jsbridge.util.CameraUtil;
import com.apkfuns.jsbridge.util.TakePhotoResult;
import com.apkfuns.jsbridge.util.WebEvent;
import com.apkfuns.jsbridge.view.base.BaseAbility;
import com.apkfuns.jsbridge.view.slice.WebViewAbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

import java.io.File;

public class WebViewAbility extends BaseAbility  implements WebEvent {
    private static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_APP, 0x00213, "WebViewAbility");
    private TakePhotoResult result;
    private String imagePath;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setMainRoute(WebViewAbilitySlice.class.getName());

    }


    @Override
    public void takePhoto(TakePhotoResult r) {

        this.result = r;
        imagePath = getExternalCacheDir().getPath() + File.separator+"picture_001.jpg";


        File outputFile = new File(imagePath);
        if (outputFile.exists()) {
            try {
                outputFile.delete();
            } catch (SecurityException  e){

            }

        }

        Intent intent = new Intent();

        Operation operation = new Intent.OperationBuilder()
                .withDeviceId("")
                .withBundleName(getBundleName())
                .withAbilityName("com.apkfuns.jsbridge.view.CameraAbility")
                .build();

        intent.setOperation(operation);

        intent.setParam("imagePath", imagePath);
        startAbilityForResult(intent,0);

    }

    @Override
    protected void onAbilityResult(int requestCode, int resultCode, Intent resultData) {
        super.onAbilityResult(requestCode, resultCode, resultData);
        if (requestCode == 0 && imagePath!=null) {

           String imageBase64Data =  CameraUtil.imageFileToBase64String(imagePath);
            HiLog.info(LABEL, "imageBase64Data " + imageBase64Data);
            if (result != null) {
                result.onSuccess(imageBase64Data);
            }
        } else {
            if (result != null) {
                result.onFailure("user cancel");
            }
        }
    }
    
}
